import type {
    IWorkflowStateListPresenter,
    IWorkflowStateListPresenterListParams,
    IWorkflowStateListPresenterListParamsWhere
} from "./abstractions/WorkflowStateListPresenter.js";
import type {
    IWorkflowStateListRepository,
    WorkflowStateListRepositoryType
} from "~/Repositories/index.js";
import { makeAutoObservable } from "mobx";

interface IWorkflowStateListPresenterParams {
    repository: IWorkflowStateListRepository;
}

export class WorkflowStateListPresenter implements IWorkflowStateListPresenter {
    private readonly repository: IWorkflowStateListRepository;

    private listParams: IWorkflowStateListPresenterListParams | undefined = undefined;

    public get vm() {
        return {
            items: this.repository.items,
            loading: this.repository.loading,
            error: this.repository.error,
            totalCount: this.repository.meta?.totalCount || 0,
            hasMoreItems: this.repository.meta?.hasMoreItems || false,
            where: this.listParams?.where || {},
            type: this.repository.type
        };
    }

    public constructor(params: IWorkflowStateListPresenterParams) {
        this.repository = params.repository;

        makeAutoObservable(this);
    }

    filterBy = async (where: IWorkflowStateListPresenterListParamsWhere): Promise<void> => {
        return await this.list({
            ...this.listParams,
            after: undefined,
            where
        });
    };

    nextPage = async (): Promise<void> => {
        if (!this.repository.meta?.hasMoreItems) {
            console.warn("No more items to load.");
            return;
        }
        return await this.repository.list({
            ...this.listParams,
            after: this.repository.meta?.cursor || undefined
        });
    };

    list = async (params?: IWorkflowStateListPresenterListParams): Promise<void> => {
        this.listParams = {
            after: undefined,
            ...params,
            limit: 50,
            where: {
                ...params?.where,
                isActive: true
            }
        };
        return await this.repository.list(this.listParams);
    };

    setType = async (type: WorkflowStateListRepositoryType): Promise<void> => {
        this.repository.setType(type);
        return await this.repository.list(this.listParams);
    };
}
